package drive.RealService;

import com.google.gson.Gson;
import drive.Mapper.ArticleMapper;
import drive.Mapper.FavoriteRecordMapper;
import drive.Mapper.FollowRelationMapper;
import drive.Mapper.ReportRecordMapper;
import drive.Model.Article;
import drive.Model.FavoriteRecord;
import drive.Model.FollowRelation;
import drive.Model.ReportRecord;
import drive.pojo.NetWork;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceB implements ArticleServiceC {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private FavoriteRecordMapper favoriteRecordMapper;

    @Autowired
    private ReportRecordMapper reportRecordMapper;

    @Autowired
    private FollowRelationMapper followRelationMapper;

    @Autowired
    private NetWork netWork;

    private Gson gson = new Gson();
    @Override
    //img_url为图片列表
    public String add(Article article, String img_url) throws JSONException, IOException {
        article.setCreationTime(new Date());
        String tag = netWork.getKeyWord(article.getTitle(),article.getContent());
        article.setTag(tag);
        articleMapper.add(article);
        int articleID = article.getArticleID();
        //补充图片表
        System.out.println(img_url);
        return "发布文章成功";
    }

    @Override
    public String findById(int articleID) {
        Article article = articleMapper.findById(articleID);
        return gson.toJson(article);
    }

    @Override
    public String search(String keyword){
        List<Article> list = articleMapper.selectArticlesByKeyword(keyword);
        return gson.toJson(list);
    }

    @Override
    @Transactional
    public String favorite(FavoriteRecord favoriteRecord){
        favoriteRecord.setCreationTime(new Date());
        favoriteRecord.setContentType(FavoriteRecord.Status.article);
        favoriteRecordMapper.add(favoriteRecord);
        articleMapper.updateArticleFavoriteCountByArticleID(favoriteRecord.getContentID());
        return "收藏成功";
    }

    @Override
    @Transactional
    public String reportArticle(ReportRecord reportRecord){
        reportRecord.setReportType(ReportRecord.ReportType.article);
        reportRecord.setSubmissionTime(new Date());
        reportRecord.setReportStatus(ReportRecord.Status.pending);
        reportRecordMapper.add(reportRecord);
        //添加redis防止重复举报

        return "举报成功";
    }

    @Override
    public String follow(FollowRelation followRelation){
        followRelation.setCreateTime(new Date());
        followRelationMapper.add(followRelation);
        return "关注成功";
    }


}
